<?php
declare(strict_types=1);

namespace App\Model\PssModel;

use App\Service\AppService\ExportExcelHandleService;
use App\Service\Code\Normal;
use App\Model\BaseModel\BasePssModel;
use App\Service\BaseService;

/**
 * 商户资金记录
 */
class Accountlog extends BasePssModel
{
    //指定表
    protected $table = 'accountlog';
    //指定写入字段
    protected $fillable = [
        'id',
        'uid',
        'type',
        'order_sn',
        'supplier_psn',
        'supplier_csn',
        'supplier_dsn',
        'symbol',
        'amount',
        'after_balance',
        'before_balance',
        'remark',
        'cd',
        'md',
        'df',
    ];

    /**
     * 类型（1、订单货款下单支付 2、订单退款 3、充值 、4 充值退款  5 、商城充值）
     */
    public static $type = [
        1 => '订单货款',
        2 => '订单退款',
        3 => '充值',
        4 => '充值退款',
        5 => '商城充值'
    ];
    
    /**
     * 写入资金日志
     * @param array $param
     */
    public static function writelog( $param = [] ){
        $log = [
            'uid'               => $param['uid'],
            'type'              => $param['type'],
            'symbol'            => $param['symbol'],
            'amount'            => $param['amount'],
            'after_balance'     => $param['after_balance'],
            'before_balance'    => $param['before_balance'],
            'remark'            => $param['remark'],
            'order_sn'          => $param['order_sn'],
            'supplier_psn'      => $param['supplier_psn'],
            'supplier_csn'      => $param['supplier_csn'],
            'supplier_dsn'      => $param['supplier_dsn'],
            'cd'                => $param['cd'],
        ];
        $res = self::make($log)->save();
        if ( !$res ) {
            return Normal::returnCode(Normal::FAIL,"操作失败");
        }
        return Normal::returnCode(Normal::SUC,"操作成功");
    }

    /**
     * 获取渠道商自己的充值退款记录
     * @param array $param
     */
    public function getUserAccoutLogList( $param = [] )
    {
        $body   = $param['body'];
        $binfo  = $param['binfo'];
        $page   = isset($body['page']) ? $body['page'] : 1 ;
        $limit  = isset($body['limit']) ? $body['limit'] : 10 ;
        $columns = [
            "order_sn",
            "type",
            "symbol",
            "amount as money",
            "remark",
            "cd"
        ];
        
        $page_data = $this->where('uid',$binfo['bid'])->whereIn('type',[3,4,5])
        ->orderBy("cd","desc")->paginate($limit, $columns, 'page', $page)->toArray();
        
        $pageRechargeOrder = array_filter(array_column($page_data['data'],'order_sn'));
        if( $pageRechargeOrder ) {
            $listRechargeOrder  = OrderRecharge::instance()->where('bid',$binfo['bid'])->whereIn('order_sn',$pageRechargeOrder)->get()->toArray();
            $listRechargeOrder  = array_column($listRechargeOrder,null,'order_sn');
        }
        
        foreach ($page_data['data'] as & $item ) {
            $type = $item['type'];
            $order_sn = $item['order_sn'];
            if( $type == 5 && isset(self::$type[$type]) && isset($listRechargeOrder[$order_sn]) ) {
                $value['cd']                    = date("Y-m-d Y-m-d H:i:s",$listRechargeOrder[$order_sn]['cd']);
                $value['md']                    = $listRechargeOrder[$order_sn]['md'] ? date("Y-m-d",$listRechargeOrder[$order_sn]['md']) : '';
                $item['recharge_status_name']   = OrderRecharge::instance()->recharge_status[$listRechargeOrder[$order_sn]['recharge_status']]??'';
                $item['pay_way_name']           = OrderSupplier::instance()->pay_way[$listRechargeOrder[$order_sn]['pay_way']]['client_name']??'';
                $item['pay_sn']                 = $listRechargeOrder[$order_sn]['pay_sn'];
            } else {
                $cd = $item['cd'];
                $item['cd']                     = date("Y-m-d H:i:s",$cd);
                $item['md']                     = $cd ? date("Y-m-d",$cd) : '';
                $item['recharge_status_name']   = '交易成功';
                $item['pay_way_name']           = '';
                $item['pay_sn']                 = '';
            }
            $item['recharge_way']               = self::$type[$type]??'';
            $item['money']                      = ($item['symbol'] == 1 ? '+':'-') . '￥' . number_format((float)$item['money'],2);
        }
        return Normal::returnCode(Normal::SUC,"获取成功",$page_data);
    }

    /**
     * 获取渠道商自己的充值退款记录
     * @param array $param
     */
    public function getAccoutLogList( $param = [] )
    {
        $body   = $param['body'];
        $binfo  = $param['binfo'];
        $page   = isset($body['page']) ? $body['page'] : 1 ;
        $limit  = isset($body['limit']) ? $body['limit'] : 10 ;
        $columns = [
            'id',
            "order_sn",
            'supplier_csn',
            "type",
            "symbol",
            "amount as money",
            'after_balance',
            'before_balance',
            "remark",
            "cd"
        ];

        $where = [];
        $order_start_time = !empty($body['cd_start_date']) ? strtotime($body['cd_start_date']) : 0 ;
        $order_end_time  = !empty($body['cd_end_date']) ? strtotime($body['cd_end_date']) + 86399 : 0 ;
        if( !empty($order_start_time) && !empty($order_end_time) ) {
            $where[]=['cd','>=',$order_start_time];
            $where[]=['cd','<=',$order_end_time];
        } else if( !empty($order_start_time) ) {
            $where[]=['cd','>=',$order_start_time];
        } else if( !empty($order_end_time) ) {
            $where[]=['cd','<=',$order_end_time];
        }

        $page_data = $this->where($where)->where('uid',$binfo['bid'])->orderBy("cd","desc")->paginate($limit, $columns, 'page', $page)->toArray();

        foreach ($page_data['data'] as & $item ) {
            $type = $item['type'];
            $item['cd']                         = date("Y-m-d H:i:s",$item['cd']);
            $item['recharge_way']               = self::$type[$type]??'';
            $item['money']                      = ($item['symbol'] == 1 ? '+':'-') . '￥' . number_format((float)$item['money'],2);
        }
        return Normal::returnCode(Normal::SUC,"获取成功",$page_data);

    }

    /**
     * 导出渠道商自己的充值退款记录
     * @param array $param
     */
    public function accoutLogListExport($param = [])
    {
        $body   = $param['body'];
        $binfo  = $param['binfo'];
        $page   = isset($body['page']) ? $body['page'] : 1 ;
        $limit  = isset($body['limit']) ? $body['limit'] : 10 ;
        $columns = [
            'id',
            "order_sn",
            'supplier_csn',
            "type",
            "symbol",
            "amount as money",
            'after_balance',
            'before_balance',
            "remark",
            "cd"
        ];
        $head = [
            '变更类型',
            '变更金额',
            '变动前的余额',
            '变更后的金额',
            '渠道订单编号',
            '供应商订单编号',
            '变更时间',
        ];

        $where = [];
        $order_start_time   = !empty($body['cd_start_date']) ? strtotime($body['cd_start_date']) : 0 ;
        $order_end_time     = !empty($body['cd_end_date']) ? strtotime($body['cd_end_date']) + 86399 : 0 ;
        if( !empty($order_start_time) && !empty($order_end_time) ) {
            $where[]=['cd','>=',$order_start_time];
            $where[]=['cd','<=',$order_end_time];
        } else if( !empty($order_start_time) ) {
            $where[]=['cd','>=',$order_start_time];
        } else if( !empty($order_end_time) ) {
            $where[]=['cd','<=',$order_end_time];
        }

        $page = 1;
        $data = [];
        while (true)
        {
            $page_data = $this
            ->where($where)
            ->where('uid',$binfo['bid'])
            ->orderBy("cd","desc")
            ->paginate(BaseService::DOWNLOAD_PAGE_SIZE, $columns, 'page', $page)
            ->toArray();
            
            if (empty($page_data['data'])){
                break;
            }
            
            foreach ($page_data['data'] as $item)
            {
                $data[]=
                [
                    self::$type[$item['type']]??'',
                    ($item['symbol'] == 1 ? '+':'-') . '￥' . number_format((float)$item['money'],2),
                    $item['before_balance']."\t",
                    $item['after_balance']."\t",
                    $item['order_sn']."\t",
                    $item['supplier_csn']."\t",
                    date("Y-m-d H:i:s",$item['cd']),
                ];
            }
            $page++;
        }
        
        $file_name = '/YunCangUserCenterFile/user_account_log_export_'.(date('YmdHis'));
        return ExportExcelHandleService::instance()->exportFile($head,$data,$file_name);
    }
}